#include <iostream>

using namespace std;

const int N = 12;
int a[N][N];
bool st[N][N];
bool check[N][N][N][N];
int n, k;
string path;
int dy[] = { 0, 1, 1, 1, 0, -1, -1, -1 };
int dx[] = { -1, -1, 0, 1, 1, 1, 0, -1 };


void dfs(int cx, int cy)
{
	if (cx == n && cy == n)
	{

		if (path.size() == n * n - 1)
		{
			cout << path << endl;
			exit(0);
		}
		return;
	}
	for (int k = 0; k < 8; k++)
	{
		int nx = cx + dx[k], ny = cy + dy[k];
		if (nx < 1 || ny < 1 || nx > n || ny > n) continue;
		if (st[nx][ny] || a[nx][ny] != (a[cx][cy] + 1) % k) continue;
		if (k == 3 || k == 7 || k == 1 || k == 5)
		{
			if (k == 3 && check[cx + 1][cy][cx][cy + 1] || check[cx][cy + 1][cx + 1][cy]) continue;
			else if (k == 7 && check[cx - 1][cy][cx][cy - 1] || check[cx][cy - 1][cx - 1][cy]) continue;
			else if (k == 1 && check[cx][cy + 1][cx - 1][cy] || check[cx - 1][cy][cx][cy + 1]) continue;
			else if (k == 5 && check[cx + 1][cy][cx][cy - 1] || check[cx][cy - 1][cx + 1][cy]) continue;
			check[cx][cy][nx][ny] = check[nx][ny][cx][cy] = true;
			st[nx][ny] = true;
			path.push_back(k + '0');
			dfs(nx, ny);
			check[cx][cy][nx][ny] = check[nx][ny][cx][cy] = false;
			st[nx][ny] = false;
			path.pop_back();

		}
		else
		{
			path.push_back(k + '0');
			st[nx][ny] = true;
			dfs(nx, ny);
			st[nx][ny] = false;
			path.pop_back();
		}
	}
}

int main()
{
	cin >> n >> k;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			cin >> a[i][j];
			if (a[i][j] >= k || a[i][j] < 0 || n * n % k != 0)
			{
				cout << -1 << endl;
				return 0;
			}

		}
	}
	st[1][1] = true;
	dfs(1, 1);
	cout << "-1" << endl;
	return 0;
}

